import { defineStore } from 'pinia'
import { ref } from 'vue'
import { routesUpgradeLevels } from '@/utils'
import { userStore } from './index'
import { RouteMeta, RouteRecordName, RouteRecordRaw } from 'vue-router'
import { isArray } from 'lodash-es'
import { dynamicRoutes } from '@/router'
import { db } from '@/storage'
import { checkAuth } from '@/utils'

const appStore = defineStore('app', () => {
  const showDrawer = ref(false)

  const userMenus = userStore().permission

  // 控制全屏
  const viewScreen = ref(false)
  const mainName = ref(db.get('mainName') || '')
  const systemModelTitle = ref(db.get('systemModelTitle') || '')

  // 默认展示路由
  const defaultRoutesMenus = ref()
  const loading = ref(false)
  const isLock = ref(db.get('lock') || false)

  // 缓存
  const keepAliveRouterMap = ref(new Map())

  // 添加视图缓存
  const addRouterViewsKeepAlive = (
    name: RouteRecordName | null | undefined,
    meta: RouteMeta
  ) => {
    // 如果视图需要缓存（keepAlive），则将其路由名称添加到缓存视图列表中
    if (meta.keepAlive) {
      keepAliveRouterMap.value.set(name, name)
    }
  }

  // 删除视图缓存
  const delRouterViewsKeep = (path: string | undefined | number) => {
    if (!path) return
    if (keepAliveRouterMap.value.has(path)) {
      keepAliveRouterMap.value.delete(path)
    }
  }

  const openDrawer = () => {
    showDrawer.value = true
  }

  const closeDarwer = () => {
    showDrawer.value = false
  }

  // 获取有权限菜单或不需要权限的菜单
  // 针对多体
  const getMenus = (
    routes: RouteRecordRaw[] = dynamicRoutes
  ): RouteRecordRaw[] => {
    return routes
      .map((item) => {
        let _temp: any = {}
        if (
          !(item.meta && item.meta?.hiddenInMenu) &&
          (item.meta?.notAuth || checkAuth(item.name as string))
        ) {
          _temp = {
            ...item,
            children: getMenus(item.children || [])
          }
        } else {
          _temp = undefined
        }
        return _temp
      })
      .filter((x) => x)
  }

  // 只针对单体
  const getFirstMenu = (menus: any[] = dynamicRoutes) => {
    return menus.filter(
      (item) =>
        !(item.meta && item.meta?.hiddenInMenu) &&
        (item.meta?.notAuth || checkAuth(item.name))
    )
  }

  const transformRoutesKeys = (
    routes: RouteRecordRaw[] = dynamicRoutes
  ): any => {
    const menus: RouteRecordRaw[] = routesUpgradeLevels(routes)
    return menus
  }

  // 设置权限菜单 --- > 废弃
  const setUserMens = (menus: any) => {
    return menus
      .filter((item: any) => {
        if (!item.children && userMenus.includes(item.name)) {
          return true
        } else if (
          isArray(item.children) &&
          item.children.length &&
          userMenus.includes(item.name)
        ) {
          return {
            ...item,
            children: setUserMens(item.children)
          }
        }
        return false
      })
      .filter((v: RouteRecordRaw) => v)
  }

  const useBreadcrumbMenus = (route: any) => {
    // 针对 children 只有 一个
    if (
      isArray(route.matched) &&
      route.matched.length &&
      isArray(route.matched[0].children) &&
      route.matched[0].children.length === 1
    ) {
      return [route.matched[route.matched.length - 1]]
    }
    return route.matched
  }

  const filterHiddenInBread = (menus: RouteRecordRaw[]) => {
    return menus
      .map((i) => ({ ...i }))
      .filter((route) => route.meta && !route.meta?.hiddenInBread)
  }

  const changeSreen = (screen: boolean) => {
    viewScreen.value = screen
  }

  const changeLoading = (loadings: boolean) => {
    loading.value = loadings
  }

  const changeMainName = (name: string, title: string) => {
    return new Promise((resovle) => {
      mainName.value = name
      systemModelTitle.value = title
      isLock.value = true
      db.set('mainName', name)
      db.set('systemModelTitle', title)
      // 多模块上锁
      db.set('lock', true)
      resovle(name)
    })
  }

  return {
    showDrawer,
    openDrawer,
    closeDarwer,
    transformRoutesKeys,
    defaultRoutesMenus,
    viewScreen,
    changeSreen,
    useBreadcrumbMenus,
    getMenus,
    getFirstMenu,
    loading,
    changeLoading,
    changeMainName,
    mainName,
    systemModelTitle,
    isLock,
    filterHiddenInBread,
    delRouterViewsKeep,
    addRouterViewsKeepAlive,
    keepAliveRouterMap
  }
})

export { appStore }
